package com.ftg.learn.springbootmq.work.Producer;

import com.alibaba.fastjson2.JSON;
import com.ftg.learn.springbootmq.work.entity.StudentEntity;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 消息生产者
 *
 */
@Component
public class MessageProducer {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送简单字符串消息
     *
     * @param message 消息内容
     */
    public void sendStringMessage(String message,String operator) {
        Map<String, Object> messageBody = new HashMap<>();
        messageBody.put("body",message);
        messageBody.put("operator",operator);
        String str = JSON.toJSONString(messageBody);
        rabbitTemplate.convertAndSend("work.queue", str.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 发送结构化消息
     *
     * @param content 消息内容
     */
    public void sendStructuredMessage(String content) {
        Map<String, Object> messageBody = new HashMap<>();
        messageBody.put("id", UUID.randomUUID().toString());
        messageBody.put("content", content);
        messageBody.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        messageBody.put("type", "work_message");

        rabbitTemplate.convertAndSend("work.queue", messageBody);
    }

    public void sendStructuredMessage(StudentEntity content,String operator) {
        Map<String, Object> messageBody = new HashMap<>();
        messageBody.put("body",content);
        messageBody.put("operator",operator);
        String str = JSON.toJSONString(messageBody);
        rabbitTemplate.convertAndSend("work.queue", str.getBytes(StandardCharsets.UTF_8));
    }
}

